package com.fhd.servlet;

import com.fhd.constant.Constants;
import com.fhd.dao.Recharge.RechargeDao;
import com.fhd.pojo.Merchant;
import com.fhd.pojo.Recharge;
import com.fhd.service.Client.ClientService;
import com.fhd.service.Client.ClientServiceImplement;
import com.fhd.service.Merchant.MerchantService;
import com.fhd.service.Merchant.MerchantServiceImplement;
import com.fhd.service.Recharge.RechargeService;
import com.fhd.service.Recharge.RechargeServiceImplement;
import com.mysql.cj.util.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.joda.time.DateTime;
import org.junit.Test;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Objects;

public class ManagerServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (Objects.equals(method,"getAllRecharge")) {
            getAllRecharge(req, resp);
        } else if (Objects.equals(method,"changeRechargeSituation")) {
            changeRechargeSituation(req, resp);
        } else if (Objects.equals(method,"managerLogout")) {
            managerLogout(req, resp);
        } else if (Objects.equals(method,"getAllMerchant")) {
            getAlLMerchant(req, resp);
        } else if (Objects.equals(method,"changeMerchantAppluSituation")) {
            changeMerchantAppluSituation(req, resp);
        } else if (Objects.equals(method,"downloadMerchantExcel")) {
            downloadMerchantExcel(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    // 获取所有的充值数据
    public void getAllRecharge(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       // 控制层调用业务层
        RechargeService rechargeService = new RechargeServiceImplement();
        ArrayList<Recharge> recharges = rechargeService.getAllRecharge();

        if (recharges != null && !recharges.isEmpty()) {
            // 把充值数据放进Session中
            req.getSession().setAttribute(Constants.GET_ALL_RECHARGE_SESSION,recharges);
        } else {
            // 告知错误信息
            req.getSession().setAttribute(Constants.GET_ALL_RECHARGE_MESSAGE,"暂且没有充值记录");
        }
        resp.sendRedirect("jsp/managerRecharge.jsp");
    }

    // 改变充值数据的状态
    public void changeRechargeSituation(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String rechargeSituation = req.getParameter("rechargeSituation");
        int id = Integer.parseInt(req.getParameter("id"));
        int clientId = Integer.parseInt(req.getParameter("clientId"));
        int money = Integer.parseInt(req.getParameter("money"));
        int row1 = 0,row2 = 0;
        if (Objects.equals(rechargeSituation,"通过")) {
            // 通过，改变充值数据，把钱加到客户的余额中
            RechargeService rechargeService = new RechargeServiceImplement();
            row1 = rechargeService.managerChangeRechargeSituation(id, 2);
            ClientService clientService = new ClientServiceImplement();
            row2 = clientService.updateMoney(clientId, money);
            if (row1 > 0 && row2 > 0) {
                // 更改数据成功
                req.getSession().setAttribute(Constants.UPDATE_RECHARGE_SITUATION_MESSAGE,"操作成功");
            } else {
                // 更改失败
                req.getSession().setAttribute(Constants.UPDATE_RECHARGE_SITUATION_MESSAGE,"操作失败");
            }

        } else {
            // 取消，改变充值数据即可
            RechargeService rechargeService = new RechargeServiceImplement();
            row1 = rechargeService.managerChangeRechargeSituation(id, 3);
            if (row1 > 0) {
                // 更改数据成功
                req.getSession().setAttribute(Constants.UPDATE_RECHARGE_SITUATION_MESSAGE,"操作成功");
            } else {
                // 更改数据失败
                req.getSession().setAttribute(Constants.UPDATE_RECHARGE_SITUATION_MESSAGE,"操作失败");
            }
        }
        resp.sendRedirect("manager.do?method=getAllRecharge");
    }

    // 退出管理员登录
    public void managerLogout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.getSession().removeAttribute(Constants.MANAGER_SESSION);
        resp.sendRedirect("login.jsp");
    }

    // 获得所有商户信息，并跳转到商户审核管理页
    public void getAlLMerchant(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 控制层调用业务层
        MerchantService merchantService = new MerchantServiceImplement();
        ArrayList<Merchant> merchants = merchantService.getAllMerchant();

        if (merchants != null && !merchants.isEmpty()) {
            // 把商户信息放进
            req.getSession().setAttribute(Constants.GET_ALL_MERCHANT_SESSION,merchants);
        } else {
            // 没有商户，告知错误信息
            req.getSession().setAttribute(Constants.GET_ALL_MERCHANT_MESSAGE,"没有商家");
        }
        resp.sendRedirect("jsp/managerMerchant.jsp");
    }

    // 改变商户申请状态
    public void changeMerchantAppluSituation(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取数据
        int id = Integer.parseInt(req.getParameter("id"));
        int situation;
        String parameter = req.getParameter("rechargeSituation");
        if(Objects.equals(parameter,"通过")) {
            situation = 1;
        } else {
            situation = 2;
        }

        // 控制层调用业务层
        MerchantService merchantService = new MerchantServiceImplement();
        int row = 0;
        row = merchantService.changeApplyMerchant(id, situation);

        // 判断结果，页面跳转
        if (row > 0) {
            // 更改成功
            req.getSession().setAttribute(Constants.UPDATE_MERCHANT_APPLY_SITUATION_MESSAGE,"操作成功");
        } else {
            // 更改失败
            req.getSession().setAttribute(Constants.UPDATE_MERCHANT_APPLY_SITUATION_MESSAGE,"操作失败，请重试");
        }
        resp.sendRedirect("manager.do?method=getAllMerchant");
    }

    public void downloadMerchantExcel(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 获取所有商户
        ArrayList<Merchant> merchants = (ArrayList<Merchant>) req.getSession().getAttribute(Constants.GET_ALL_MERCHANT_SESSION);
        if (merchants != null && !merchants.isEmpty()) {

            // 写xlsx文件
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("商户信息表");
            // 写出第一行
            Row row1 = sheet.createRow(0);
            Cell cell1_1 = row1.createCell(0);
            cell1_1.setCellValue("商户id");
            Cell cell1_2 = row1.createCell(1);
            cell1_2.setCellValue("商户账号");
            Cell cell1_3 = row1.createCell(2);
            cell1_3.setCellValue("商户密码");
            Cell cell1_4 = row1.createCell(3);
            cell1_4.setCellValue("商户昵称");
            Cell cell1_5 = row1.createCell(4);
            cell1_5.setCellValue("店铺名");
            Cell cell1_6 = row1.createCell(5);
            cell1_6.setCellValue("地址");
            Cell cell1_7 = row1.createCell(6);
            cell1_7.setCellValue("联系电话");
            Cell cell1_8 = row1.createCell(7);
            cell1_8.setCellValue("关键词");
            Cell cell1_9 = row1.createCell(8);
            cell1_9.setCellValue("工作开始时间");
            Cell cell1_10 = row1.createCell(9);
            cell1_10.setCellValue("工作结束时间");
            Cell cell1_11 = row1.createCell(10);
            cell1_11.setCellValue("营业状态");
            Cell cell1_12 = row1.createCell(11);
            cell1_12.setCellValue("申请状态");
            Cell cell1_13 = row1.createCell(12);
            cell1_13.setCellValue("商户收入");
            Cell cell1_14 = row1.createCell(13);
            cell1_14.setCellValue("销售量");
            Cell cell1_15 = row1.createCell(14);
            cell1_15.setCellValue("创建时间");

            // 写出商户信息
            for (int i = 0;i < merchants.size();i ++) {
                Row rowi = sheet.createRow(i + 1);
                Merchant merchant = merchants.get(i);
                rowi.createCell(0).setCellValue(merchant.getId());
                rowi.createCell(1).setCellValue(merchant.getUserCode());
                rowi.createCell(2).setCellValue(merchant.getUserPassword());
                rowi.createCell(3).setCellValue(merchant.getUserName());
                rowi.createCell(4).setCellValue(merchant.getShopName());
                rowi.createCell(5).setCellValue(merchant.getAddress());
                rowi.createCell(6).setCellValue(merchant.getPhone());
                rowi.createCell(7).setCellValue(merchant.getKeyWord());

                rowi.createCell(8).setCellValue(new DateTime(merchant.getWorkTimeBegin()).toString("HH:mm:ss"));
                rowi.createCell(9).setCellValue(new DateTime(merchant.getWorkTimeEnd()).toString("HH:mm:ss"));
                int openSituation = merchant.getOpenSituation();
                if (openSituation == 0) {
                    rowi.createCell(10).setCellValue("未营业");
                } else {
                    rowi.createCell(10).setCellValue("营业中");
                }
                int applySituation = merchant.getApplySituation();
                if (applySituation == 0) {
                    rowi.createCell(11).setCellValue("待确认");
                } else if (applySituation == 1) {
                    rowi.createCell(11).setCellValue("已通过");
                } else {
                    rowi.createCell(11).setCellValue("被封禁");
                }
                rowi.createCell(12).setCellValue(merchant.getMoney());
                rowi.createCell(13).setCellValue(merchant.getSoldNumber());
                rowi.createCell(14).setCellValue(new DateTime(merchant.getCreateDate()).toString("yyyy-MM-dd"));
            }

            String path = "D:\\code\\idea\\LiveWherever\\src\\main\\webapp\\download\\MerchantInformation.xlsx";

            FileOutputStream fileOutputStream = null;
            try {
                // 写文件
                fileOutputStream = new FileOutputStream(path);
                workbook.write(fileOutputStream);
                System.out.println("输出完毕");
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            }

            // 下载文件
            File file = new File(path);
            FileInputStream is = null;
            ServletOutputStream os = null;
            try {
                if (file.exists() && file.isFile()) {
                    resp.setContentType("application/x-msdownload");
                    resp.setHeader("Content-Disposition", "attachment;filename=MerchantInformation.xlsx");

                    is = new FileInputStream(file);
                    os = resp.getOutputStream();

                    byte[] buffer = new byte[1024];
                    int len = 0;
                    while ((len = is.read(buffer)) != -1) {
                        os.write(buffer,0,len);
                    }
                }
            } finally {
                if (os != null) {
                    os.close();
                }
                if (is != null) {
                    is.close();
                }
            }

        }
    }
}
